Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
Sort array of arrays with string values [JavaScript]

I ran across a paradox where sorting arrays works for number or number string values only. Here is the example:

const sortArr = (a, b) => a[1] - b[1];

const arr1 = [['two', '2'], ['one', '1'], ['three', '3']];
const arr2 = [['WA', 'Washington'], ['NC', 'North Carolina'], ['PA', 'Pennsylvania']];

let sortedArr1 = arr1.sort(sortArr);
let sortedArr2 = arr2.sort(sortArr);

console.log('sortedArr1', sortedArr1);  // returns sorted array
console.log('sortedArr2', sortedArr2);  // returns original array (not sorting)

Can someone help figure out the right ways how to sort arr2 by second values correctly? Thank you!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Subtraction only works as the comparison function when you're comparing numbers. You need a comparison function that works with both numbers and strings.

function sortArr(a, b) {
    if (a == b) {
        return 0;
    else if (a < b) {
        return -1;
    } else {
        return 1;
    }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!